package jok.properties;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Set;

import jok.io.FileDemo;

public class PropertiesDemo {

	public static void main(String[] args) {

		// setAndGet();

		// listProp();

		storeProp();

		loadProp();

		FileDemo.deleteFile("D:/a.txt");
	}

	public static void setAndGet() {
		Properties prop = new Properties();

		prop.setProperty("id", "1");
		prop.setProperty("name", "张三");
		prop.setProperty("age", "18");

		System.out.println("id=" + prop.getProperty("id"));
		System.out.println("name=" + prop.getProperty("name"));
		System.out.println("age=" + prop.getProperty("age"));
	}

	public static void listProp() {
		Properties prop = new Properties();

		prop.setProperty("id", "1");
		prop.setProperty("name", "张三");
		prop.setProperty("age", "18");

		PrintWriter pw = null;
		try {
			pw = new PrintWriter(new FileWriter("D:/a.txt"), true);
			prop.list(pw);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (pw != null)
				pw.close();
		}
	}

	public static void loadProp() {
		Properties prop = new Properties();

		FileReader fr = null;
		try {
			fr = new FileReader("D:/a.txt");
			prop.load(fr);
			Set<Object> set = prop.keySet();
			for (Object object : set) {
				System.out.println((String) object + "="
						+ prop.getProperty((String) object));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fr != null)
					fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void storeProp() {
		Properties prop = new Properties();

		prop.setProperty("id", "1");
		prop.setProperty("name", "张三");
		prop.setProperty("age", "18");

		PrintWriter pw = null;
		try {
			pw = new PrintWriter(new FileWriter("D:/a.txt"), true);
			prop.store(pw, "momoda");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (pw != null)
				pw.close();
		}
	}
}
